"""socket_web服务器"""

import socket
import os
# 相当于路由
def response_for_path(path):
    _dict = {
        '/':index,
        '/doge.gif':dog_img,
    }
    return _dict.get(path,error_404)()

# 主页视图函数'/'
def index():
    header = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n'
    body = '<h1>Hello World</h1><img src="doge.gif"/>'
    response = header +'\r\n'+ body
    return response.encode('utf-8')

def dog_img():
    d = os.path.dirname(__file__)
    path = d+'/doge.gif'
    with open(path, 'rb') as f:
        header = b'HTTP/1.1 200 OK\r\nContent-Type: image/gif\r\n'
        img = header +b'\r\n'+ f.read()
        return img

def error_404():
    response = b'HTTP/1.x 404 NOT FOUND\r\n\r\n<h1>NOT FOUND</h1>'
    return response

if __name__ == '__main__':
    s = socket.socket()
    s.bind(('127.0.0.1',2000))
    while True:
        s.listen(5) # 套路
        connection, address = s.accept()
        request = connection.recv(1024)
        request = request.decode('utf-8')
        print('ip and request, {}\n{}\n'.format(address, request))

        # 获得url字符串
        path = request.split()[1]

        response = response_for_path(path)

        connection.sendall(response)
        connection.close()
    s.close()